package com.qk.management.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.domain.role.RoleDO;
import com.qk.dto.role.RoleDTO;
import com.qk.entity.Role;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public Result list(RoleDTO roleDTO) {
        PageHelper.startPage(roleDTO.getPage(), roleDTO.getPageSize());
        List<RoleDO> list = roleMapper.selectByPage(roleDTO);
        Page<RoleDO> page = (Page<RoleDO>) list;
        PageResult<RoleDO> pageResult = PageResult.<RoleDO>builder()
                .total(Math.toIntExact(page.getTotal()))
                .rows(page.getResult())
                .build();
        return Result.success(pageResult);
    }

    @Override
    public Result add(Role role) {
        if (role.getName() == null || role.getName().isEmpty()) {
            return Result.error("角色名称不能为空");
        }
        // 验证角色名称唯一性
        RoleDO nameConflict = roleMapper.selectByName(role.getName());
        if (nameConflict != null) {
            return Result.error("角色名称已存在");
        }
        // 验证角色标识唯一性
        RoleDO labelConflict = roleMapper.selectByLabel(role.getLabel());
        if (labelConflict != null) {
            return Result.error("角色标识已存在");
        }
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.insert(role);
        return Result.success();
    }

    @Override
    public Result update(Role role) {
        Role existingRole = roleMapper.selectById(role.getId());
        if (existingRole == null) {
            return Result.error("角色不存在");
        }
        // 验证角色名称唯一性（排除当前角色）
        RoleDO nameConflict = roleMapper.selectByName(role.getName());
        if (nameConflict != null && !nameConflict.getId().equals(role.getId())) {
            return Result.error("角色名称已存在");
        }
        // 验证角色标识唯一性（排除当前角色）
        RoleDO labelConflict = roleMapper.selectByLabel(role.getLabel());
        if (labelConflict != null && !labelConflict.getId().equals(role.getId())) {
            return Result.error("角色标识已存在");
        }
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.update(role);
        return Result.success();
    }
    @Override
    public Role selectById(Integer id) {
        return roleMapper.selectById(id);
    }

    @Override
    public void delete(Integer id) {
        roleMapper.delete(id);
    }

    @Override
    public List<Role> selectAll() {

        return roleMapper.selectAll();
    }

}
